import React, { PureComponent } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import {
  Card,
  message,
  Button,
  Table,
  Select,
  Modal,
  Form,
  Input,
  Popconfirm,
  Divider,
  Radio
} from 'antd'
import { connect } from 'dva'
import { LZFormItem } from '@/components/LZForm'
import Search from '@/components/Search'
import { downloadFile } from '@/utils/utils'
import MemberService from './services'
import departmentService from '@/services/department'
import { router } from 'umi'

const { Option } = Select
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
}

@connect()
@Form.create()
class Member extends PureComponent {
  state = {
    title: '', //modal的标题
    imgSrc: '',
    fileList: [],
    pageNumber: 1,
    pageSize: 10,
    visible: false,
    loading: true,
    addConfirmLoading: false,
    tableData: [],
    detail: {},
    departments: [],
    departmentId: '',
    name: ''
  }

  columns = [
    {
      title: '成员账号',
      dataIndex: 'mobile',
      align: 'center'
    },
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'name',
      width: 120
    },
    {
      title: '所属部门',
      dataIndex: 'departmentName',
      align: 'center'
    },
    {
      title: '邮箱地址',
      dataIndex: 'email',
      align: 'center'
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      align: 'center'
    },
    {
      title: '最后登入',
      dataIndex: 'updateTime',
      align: 'center'
    },
    {
      title: '是否启用',
      dataIndex: 'status',
      align: 'center',
      width: 200,
      render: (text, record) => {
        return (
          <Radio.Group
            defaultValue={text}
            buttonStyle="solid"
            onChange={evt => this.handleStatusChange(evt, record)}
          >
            <Radio.Button value="VALID">启用</Radio.Button>
            <Radio.Button value="INVALID">不启用</Radio.Button>
          </Radio.Group>
        )
      }
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      fixed: 'right',
      width: 140,
      render: (text, record) => (
        <div className="table-action">
          <a onClick={() => this.edit(record)}>修改</a>
          <Divider type="vertical" />
          <a onClick={() => this.editPermission(record)}>权限设置</a>
          <Divider type="vertical" />
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => this.deleteItem(record)}
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      )
    }
  ]

  componentDidMount() {
    this.initData()
    this.getDepartment()
  }

  getDepartment = () => {
    departmentService.queryAll().then(res => {
      this.setState({
        departments: res || []
      })
    })
  }

  deleteItem = record => {
    MemberService.delete({
      id: record.id
    }).then(res => {
      message.success('删除成功')
      this.initData()
    })
  }

  edit = record => {
    this.setState({
      visible: true,
      detail: record,
      title: '修改成员'
    })
  }

  editPermission = record => {
    router.push('/permission/member/config/user-' + record.id)
  }

  handleStatusChange = (evt, record) => {
    MemberService.modifyBackstageUser({
      id: record.id,
      status: evt.target.value
    }).then(res => {
      message.success('修改成功')
      this.handleFilter()
    })
  }

  //分页，下一页
  onChange = pageNumber => {
    this.setState(
      {
        pageNumber: pageNumber
      },
      () => {
        this.handleFilter({ type: 'pageChange' })
      }
    )
  }
  showTotal = () => {
    return `共有${this.state.total}条`
  }
  //切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize: pageSize,
        pageNumber: 1
      },
      () => {
        this.handleFilter()
      }
    )
  }

  add = () => {
    this.setState({
      visible: true,
      title: '添加成员',
      detail: {}
    })
  }

  close = () => {
    this.setState({
      visible: false
    })
  }
  handleExportData = () => {
    downloadFile()
  }

  initData = () => {
    let payload = {
      pageNumber: this.state.pageNumber,
      pageSize: this.state.pageSize,
      name: this.state.name,
      departmentId: this.state.departmentId
    }
    this.setState(
      {
        loading: true
      },
      () => {
        MemberService.queryBackstageUserPage(payload)
          .then(res => {
            message.success('获取信息成功')
            this.setState({
              tableData: res.records,
              total: res.total,
              loading: false,
              current: res.current
            })
          })
          .catch(err => {
            this.setState({
              loading: false
            })
          })
      }
    )
  }

  handleOk = () => {
    const { id, title, detail } = this.state
    const { form } = this.props
    form.validateFields((err, values) => {
      if (!err) {
        const service =
          title === '添加成员'
            ? MemberService.addBackstageUser
            : MemberService.modifyBackstageUser
        service({
          ...values,
          id: detail.id
        })
          .then(res => {
            this.handleFilter()
            message.success('保存成功')
          })
          .finally(() => {
            this.close()
          })
      }
    })
  }

  handleFilter = (data = {}) => {
    console.log(data)
    if (data.type && data.type === '分页') {
      this.initData()
    } else {
      this.setState(
        {
          pageNumber: data.type === 'pageChange' ? this.state.pageNumber : 1,
          pageSize: this.state.pageSize,
          name: data.memberName ? data.memberName : null,
          departmentId: data.departments ? data.departments : null
        },
        () => {
          this.initData()
        }
      )
    }
  }

  checkPassword = () => {
    return {
      validator: (rule, value, callback) => {
        const lastPassword = this.props.form.getFieldValue('password')
        if (value !== lastPassword) {
          callback('两次密码不一致!')
        }
        callback()
      }
    }
  }

  render() {
    const {
      loading,
      visible,
      addConfirmLoading,
      current,
      total,
      tableData,
      detail,
      title,
      departments
    } = this.state
    const { getFieldDecorator } = this.props.form
    const {
      name,
      mobile,
      email,
      departmentId,
      remark,
      password,
      confirmPassword
    } = detail
    let departmentsOptions =
      (departments && departments.map(v => ({ label: v.name, value: v.id }))) ||
      []
    const options = [{ field: 'departments', options: departmentsOptions }]
    const isEdit = title === '修改成员'

    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false} className="mt-20">
          <Search
            source={'成员管理'}
            options={options}
            exportData={this.handleExportData}
            handleFilter={this.handleFilter}
          />
          <Button type="primary" className="mt-20 mb-18" onClick={this.add}>
            添加成员
          </Button>
          <Table
            loading={loading}
            columns={this.columns}
            dataSource={tableData}
            scroll={{ x: true }}
            rowKey={record => record.id}
            pagination={{
              current: current,
              total: total,
              onChange: this.onChange,
              showTotal: this.showTotal,
              showQuickJumper: true,
              pageSizeOptions: ['3', '5', '10'],
              showSizeChanger: true,
              onShowSizeChange: this.onShowSizeChange
            }}
          />
        </Card>
        {/* 新增 */}
        <Modal
          title={title}
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={addConfirmLoading}
          destroyOnClose={true}
          onCancel={() => {
            this.setState({
              visible: false,
              fileList: [],
              imgSrc: ''
            })
          }}
        >
          <Form {...formItemLayout}>
            <LZFormItem
              field="mobile"
              label="手机号"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="手机号不能为空"
              initialValue={mobile}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            <LZFormItem
              field="name"
              label="成员姓名"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="成员姓名不能为空"
              initialValue={name}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            <LZFormItem
              field="email"
              label="邮箱地址"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="邮箱地址不能为空"
              initialValue={email}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            <LZFormItem
              label="所属部门"
              field="departmentId"
              key="departmentId"
              getFieldDecorator={getFieldDecorator}
              initialValue={departmentId}
            >
              <Select placeholder="所属部门" style={{ width: 200 }} allowClear>
                {departmentsOptions.map(option => {
                  return (
                    <Option value={option.value} key={option.value}>
                      {option.label}
                    </Option>
                  )
                })}
              </Select>
            </LZFormItem>
            <LZFormItem
              field="password"
              label="登入密码"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="登入密码不能为空"
              lzIf={!isEdit}
              initialValue={password}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            <LZFormItem
              field="confirmPassword"
              label="确认密码"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="确认密码不能为空"
              lzIf={!isEdit}
              rules={[this.checkPassword()]}
              initialValue={confirmPassword}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            <LZFormItem
              label="备注信息"
              field="remark"
              getFieldDecorator={getFieldDecorator}
              initialValue={remark}
            >
              <Input.TextArea rows={4} placeholder="请输入" />
            </LZFormItem>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default Member
